import fs from 'node:fs'
import path from 'node:path'
import { pathToFileURL, fileURLToPath } from 'node:url'
import { Plugin_Name } from './components/index.js'

if (!global.segment) {
  global.segment = (await import("oicq")).segment
}

if (!global.uploadRecord) {
  try {
    global.uploadRecord = (await import("./model/uploadRecord.js")).default
  } catch (err) {
    global.uploadRecord = segment.record
  }
}


//同时加载apps下的所有js，包括子目录（index.js位于插件根目录）
const pluginDir = path.dirname(fileURLToPath(import.meta.url))
const root = path.join(pluginDir, 'apps')
let files = []
let stack = [root]
while (stack.length) {
  const dir = stack.pop()
  const entries = fs.readdirSync(dir, { withFileTypes: true })
  for (const e of entries) {
    const full = path.join(dir, e.name)
    if (e.isDirectory()) stack.push(full)
    else if (e.name.endsWith('.js')) files.push(path.relative(root, full).replace(/\\/g, '/'))
  }
}

let ret = []
logger.info("--------------------------------")
logger.info(`${Plugin_Name} 载入成功`);
logger.info("开发者 3446737520");
logger.info("我们的群聊：600388843")
logger.info("更多功能正在开发中")
logger.info("--------------------------------")


files.forEach((file) => {
    const abs = path.join(root, file)
    ret.push(import(pathToFileURL(abs).href))
})

ret = await Promise.allSettled(ret)

let apps = {}
for (let i in files) {
    let name = files[i].replace(/\\/g, '/').replace('.js', '')

    if (ret[i].status != 'fulfilled') {
        logger.error(`载入插件错误：${logger.red(name)}`)
        logger.error(ret[i].reason)
        continue
    }
    apps[name] = ret[i].value[Object.keys(ret[i].value)[0]]
}
export { apps }
